package com.xytc.company.company_backend.adminEndPoint.controller;

import com.alibaba.fastjson.JSONObject;
import com.xytc.company.company_backend.common.FileConstants;
import com.xytc.company.company_backend.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author scott
 * @since 2018-12-20
 */
@Slf4j
@RestController
@RequestMapping("/company/fileUpload")
public class UploadController {

    /**
     * 文件上传统一方法
     * @param request
     * @return
     */
    @PostMapping(value = "/upload")
    public Result<?> upload(
            HttpServletResponse response,
            HttpServletRequest request) {
        String savePath = "";

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获取上传文件对象
        MultipartFile file = multipartRequest.getFile("file");
        String fileName = UUID.randomUUID() + "-" + file.getOriginalFilename();
        savePath = this.uploadLocal(file, fileName);
        JSONObject resultData = new JSONObject();
        resultData.put("filePath", savePath);
        if(StringUtils.isNotEmpty(savePath)){
            return Result.ok(resultData);
        }else {
            response.setStatus(500);
            return Result.error("上传失败！");
        }
    }

    /**
     * 本地文件上传
     * @param mf 文件
     * @return
     */
    private String uploadLocal(MultipartFile mf, String fileName){
        try {
            File uploadTempDir = new File(FileConstants.FILE_UPLOAD_TEMP_DIR);
            if (!uploadTempDir.exists()) {
                // 上传的文件，都先放在临时目录下，此处判断临时目录是否存在，若不存在，则先创建临时目录
                uploadTempDir.mkdirs();
            }

            String savePath = uploadTempDir.getPath() + File.separator + fileName;
            File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);

            return savefile.getAbsolutePath();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

}
